/**
 * 桌台暂存数据管理器
 * 负责管理每个桌台的点菜暂存数据，支持自动清理
 */
import { LocalStorage } from './storage'

interface DeskCacheData {
    selectedList: any[]
    activeIndex: number
    activeCount: number
    timestamp: number
    deskId: string
}

export class DeskStorageManager {
    private static readonly STORAGE_PREFIX = 'desk_cache_'
    private static readonly EXPIRY_TIME = 24 * 60 * 60 * 1000 // 24小时过期
    private static readonly MAX_CACHE_SIZE = 10 // 最多缓存10个桌台数据

    /**
     * 保存桌台暂存数据
     */
    static saveDeskData(deskId: string, data: {
        selectedList: any[]
        activeIndex: number
        activeCount: number
    }) {
        try {
            const cacheData: DeskCacheData = {
                ...data,
                timestamp: Date.now(),
                deskId
            }

            const key = this.STORAGE_PREFIX + deskId
            LocalStorage.set(key, JSON.stringify(cacheData))

            console.log(`桌台 ${deskId} 数据已暂存`)
        } catch (error) {
            console.error('保存桌台暂存数据失败:', error)
        }
    }

    /**
     * 加载桌台暂存数据
     */
    static loadDeskData(deskId: string): {
        selectedList: any[]
        activeIndex: number
        activeCount: number
    } | null {
        try {
            const key = this.STORAGE_PREFIX + deskId
            const cached = LocalStorage.get(key)

            if (!cached) return null

            const cacheData: DeskCacheData = JSON.parse(cached as string)

            // 检查是否过期
            if (Date.now() - cacheData.timestamp > this.EXPIRY_TIME) {
                this.clearDeskData(deskId)
                return null
            }

            return {
                selectedList: cacheData.selectedList || [],
                activeIndex: cacheData.activeIndex || -1,
                activeCount: cacheData.activeCount || 0
            }
        } catch (error) {
            console.error('加载桌台暂存数据失败:', error)
            return null
        }
    }

    /**
     * 清除指定桌台的暂存数据
     */
    static clearDeskData(deskId: string) {
        try {
            const key = this.STORAGE_PREFIX + deskId
            LocalStorage.remove(key)
            console.log(`桌台 ${deskId} 暂存数据已清除`)
        } catch (error) {
            console.error('清除桌台暂存数据失败:', error)
        }
    }

    /**
     * 清除所有桌台暂存数据
     */
    static clearAllDeskData() {
        try {
            const keys = Object.keys(localStorage)
            const deskKeys = keys.filter(key => key.startsWith(this.STORAGE_PREFIX))

            deskKeys.forEach(key => {
                localStorage.removeItem(key)
            })

            console.log(`已清除所有桌台暂存数据 (${deskKeys.length} 个)`)
        } catch (error) {
            console.error('清除所有桌台暂存数据失败:', error)
        }
    }

    /**
     * 清理过期数据
     */
    private static cleanupExpiredData() {
        try {
            const keys = Object.keys(localStorage)
            const deskKeys = keys.filter(key => key.startsWith(this.STORAGE_PREFIX))

            if (deskKeys.length === 0) return

            // 收集所有缓存项信息
            const cacheItems: Array<{ key: string; timestamp: number; data: any }> = []

            deskKeys.forEach(key => {
                try {
                    const storedData = localStorage.getItem(key)
                    if (storedData) {
                        const data = JSON.parse(storedData)
                        cacheItems.push({
                            key,
                            timestamp: data.timestamp || 0,
                            data
                        })
                    }
                } catch (error) {
                    // 解析失败的数据直接删除
                    localStorage.removeItem(key)
                    console.warn(`删除无效缓存数据: ${key}`)
                }
            })

            const now = Date.now()
            let validItems: Array<{ key: string; timestamp: number; data: any }> = []

            // 删除过期的数据（给一个缓冲时间，避免删除刚保存的数据）
            const bufferTime = 5 * 60 * 1000 // 5分钟缓冲时间
            cacheItems.forEach(item => {
                if (now - item.timestamp > (this.EXPIRY_TIME + bufferTime)) {
                    localStorage.removeItem(item.key)
                    console.log(`删除过期缓存: ${item.key}`)
                } else {
                    validItems.push(item)
                }
            })

            // 如果缓存数量超过限制，删除最旧的数据
            if (validItems.length > this.MAX_CACHE_SIZE) {
                // 按时间戳升序排序，最旧的在前
                validItems.sort((a, b) => a.timestamp - b.timestamp)

                const itemsToDelete = validItems.slice(0, validItems.length - this.MAX_CACHE_SIZE)
                itemsToDelete.forEach(item => {
                    localStorage.removeItem(item.key)
                    console.log(`删除超出限制的缓存: ${item.key}`)
                })
            }

            console.log(`缓存清理完成，当前有效缓存: ${validItems.length} 个`)
        } catch (error) {
            console.error('清理过期数据失败:', error)
        }
    }

    /**
     * 手动清理过期数据（可以在应用启动时调用）
     */
    static manualCleanup() {
        this.cleanupExpiredData()
    }

    /**
     * 获取所有桌台暂存数据概览
     */
    static getDeskCacheOverview(): Array<{
        deskId: string
        timestamp: number
        selectedListCount: number
    }> {
        try {
            const keys = Object.keys(localStorage)
            const deskKeys = keys.filter(key => key.startsWith(this.STORAGE_PREFIX))

            return deskKeys.map(key => {
                try {
                    const data: DeskCacheData = JSON.parse(localStorage.getItem(key) || '{}')
                    return {
                        deskId: data.deskId || key.replace(this.STORAGE_PREFIX, ''),
                        timestamp: data.timestamp || 0,
                        selectedListCount: data.selectedList?.length || 0
                    }
                } catch {
                    return {
                        deskId: key.replace(this.STORAGE_PREFIX, ''),
                        timestamp: 0,
                        selectedListCount: 0
                    }
                }
            })
        } catch (error) {
            console.error('获取桌台缓存概览失败:', error)
            return []
        }
    }
}

export default DeskStorageManager
